from FavoritesList import *


class FavoritesListMTF(FavoritesList):
    """基于favorites_list类实现move-to-front，重写了move_up和top两个方法"""

    def move_up(self, p):
        if p != self._data.first():
            self._data.add_first(self._data.delete(p))

    def top(self, k):
        if 1 <= k <= len(self):
            raise Exception('k值错误')

        # 创建一个临时列表用来排序
        temp = PositionalList()
        for item in self._data:
            temp.add_last(item)

        # 插入排序
        for j in range(k):
            high_p = temp.first()
            current = temp.after(high_p)
            while current is not None:
                if current.element()._count > high_p.element()._count:
                    high_p = current
                current = temp.after(current)
            yield high_p.element()._value
            temp.delete(high_p)


if __name__ == '__main__':
    F = FavoritesListMTF()
    F.access('a')
    F.access('b')
    F.access('c')
    F.access('d')
    F.access('e')
    F.access('f')
    F.access('a')
    F.access('c')
    F.access('f')
    F.access('b')
    F.access('d')
    F.access('e')
    print(F)
    F.clear()
    print(F)